import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:get/get.dart';
import 'package:zrjz/comm/base/base.dart';
import 'package:zrjz/comm/constants/constants.dart';
import 'package:zrjz/comm/utils/ex_widget.dart';
import 'package:zrjz/comm/utils/ext_dart.dart';
import 'package:zrjz/comm/utils/log_utils.dart';
import 'package:zrjz/comm/widget/common_widget.dart';
import 'package:zrjz/comm/widget/my_load_image.dart';
import 'package:zrjz/comm/widget/my_text_form_field.dart';
import 'package:zrjz/generated/assets.dart';
import 'package:zrjz/modules/me/form_filed/check_box_form_field.dart';
import 'package:zrjz/modules/me/form_filed/form_filed_state.dart';
import 'package:zrjz/router/page_router.dart';

import 'form_filed_controller.dart';

class FormFiledPage extends BaseStatefulPage<FormFiledController> {
  FormFiledPage({super.key});

  //启动当前页面
  static void startInstance() {
    return Get.start(RouterPath.FORMFILED);
  }

  @override
  FormFiledController createRawController() {
    return FormFiledController();
  }

  @override
  State<StatefulWidget> createState() => _FormFiledPageState();
}

class _FormFiledPageState extends BaseState<FormFiledPage, FormFiledController> {
  // 创建一个 GlobalKey 用于获取 FormState 对象
  final _formKey = GlobalKey<FormState>();
  late FormFiledState state;

  // 保存表单字段的值
  String? _selectedOption;

  List<String> resource = [
    '谷歌',
    '脸书',
    '抖音',
    '其他',
  ];

  @override
  void initState() {
    super.initState();
    state = controller.state;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommonWidget.appBar(context, "Form表单提交"),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: autoCtlGetBuilder(builder: (controller) {
          return Form(
            key: _formKey, // 关联 GlobalKey
            child: Column(
              children: [

                _buildInputLayout(
                  "name",
                  Assets.authLoginPhoneIcon,
                  leftIconWidth: 13.5,
                  leftIconHeight: 16,
                  marginTop: 20,
                  textInputType: TextInputType.phone,
                  textInputAction: TextInputAction.next,
                  onSaved: (value) {
                    state.formData['name']!['value'] = value;
                  },
                ),

                _buildInputLayout(
                  "email",
                  Assets.authLoginPasswordIcon,
                  leftIconWidth: 13.5,
                  leftIconHeight: 16,
                  marginTop: 20,
                  textInputType: TextInputType.phone,
                  textInputAction: TextInputAction.next,
                  onSaved: (value) {
                    state.formData['email']!['value'] = value;
                  },
                ),

                Container(
                  margin: const EdgeInsets.only(left: 20, right: 20, top: 23),
                  decoration: BoxDecoration(
                    color: DarkThemeUtil.multiColors(ColorConstants.white, darkColor: ColorConstants.darkBlackItem),
                    borderRadius: const BorderRadius.all(Radius.circular(5)),
                    border: Border.all(color: ColorConstants.secondaryAppColor, width: 0.5),
                  ),
                  padding: const EdgeInsets.only(left: 16, right: 18, top: 2.5, bottom: 2.5),
                  child: DropdownButtonFormField<String>(
                    decoration: const InputDecoration(
                      hintText: "请选择来源",
                      hintStyle: TextStyle(
                        fontSize: 14.0,
                        fontWeight: FontWeight.w500,
                      ),
                      //左侧图片
                      icon: null,
                      border: InputBorder.none,
                      //右图片
                      suffixIcon: null,
                      //框内，文本上面的提示文本
                      labelText: null,
                      errorText: null,
                      //错误信息
                      errorStyle: TextStyle(color: Colors.red, fontSize: 14),
                    ),
                    value: _selectedOption,
                    style: TextStyle(
                      color: DarkThemeUtil.multiColors(ColorConstants.tabTextBlack, darkColor: ColorConstants.white),
                      fontSize: 15.0,
                      fontWeight: FontWeight.w500,
                    ),
                    items: resource.map((String option) {
                      return DropdownMenuItem<String>(
                        value: option,
                        child: Text(option), //如果想要图片加文本，在这里修改布局即可
                      );
                    }).toList(),
                    onChanged: (value) {},
                    onSaved: (value) {
                      setState(() {
                        _selectedOption = value;
                      });
                    },
                    validator: (value) {
                      if (value == null) {
                        return 'Please select an option';
                      }
                      return null;
                    },
                  ),
                ),

                SizedBox(height: 16.0),

                CheckBoxFormField(
                  title: const Text('是否同意协议',style: TextStyle(color: Colors.black,fontSize: 14),),
                  onSaved: (value) {
                    // 处理保存逻辑
                  },
                  validator: (value) {
                    // 处理校验逻辑
                    if (value == false) {
                      return '请勾选此选项';
                    }
                    return null;
                  },
                ),

                SizedBox(height: 16.0),

                ElevatedButton(
                  onPressed: () {
                    // 验证表单字段
                    if (_formKey.currentState?.validate() == true) {
                      //可以手动的设置错误文本
                      state.formData['name']!['errorText'] = null;
                      state.formData['email']!['errorText'] = null;
                      controller.update();

                      _formKey.currentState?.save(); //调用保存
                      // 表单验证通过，可以提交表单
                      _submitForm();
                    } else {
                      Log.e("校验不通过");
                    }
                  },
                  child: const Text('提交'),
                ),

                ElevatedButton(
                  onPressed: () {
                    setState(() {
                      _selectedOption = null;
                    });
                    _formKey.currentState?.reset(); //重置
                  },
                  child: const Text('重置'),
                ),
              ],
            ),
          );
        }),
      ),
    );
  }

  void _submitForm() {
    // 在这里执行表单提交的逻辑，例如发送网络请求等
    print("当前的表单数据为：name:${state.formData['name']!['value']}  email:${state.formData['email']!['value']}");
  }

  Widget _buildInputLayout(
    String key,
    String leftIconRes, {
    double leftIconWidth = 0,
    double leftIconHeight = 0,
    double marginTop = 23,
    double paddingRight = 18,
    bool? showRightIcon = false, //是否展示右侧的布局
    Widget? rightWidget, //右侧的布局
    TextInputType textInputType = TextInputType.text,
    String? errorText,
    TextInputAction textInputAction = TextInputAction.done,
    String? Function(String? value)? validator, //自定义Form验证
    String? Function(String? value)? onSaved, //Form的保存
    Function? onSubmit,
  }) {
    return IgnoreKeyboardDismiss(
      child: MyTextFormField(
        key,
        state.formData[key]!['value'],
        hintText: state.formData[key]!['hintText'],
        hintStyle: const TextStyle(
          fontSize: 14.0,
          fontWeight: FontWeight.w500,
        ),
        margin: EdgeInsets.only(left: 20, right: 20, top: marginTop),
        showDivider: false,
        fillBackgroundColor: DarkThemeUtil.multiColors(ColorConstants.white, darkColor: ColorConstants.darkBlackItem),
        fillCornerRadius: 5,
        padding: EdgeInsets.only(left: 16, right: paddingRight, top: 2.5, bottom: 2.5),
        height: 50,
        style: TextStyle(
          color: DarkThemeUtil.multiColors(ColorConstants.tabTextBlack, darkColor: ColorConstants.white),
          fontSize: 14.0,
          fontWeight: FontWeight.w500,
        ),
        inputType: textInputType,
        textInputAction: textInputAction,
        onSubmit: onSubmit,
        validator: validator ?? state.formData[key]!['validator'],
        onSaved: onSaved,
        cursorColor: ColorConstants.tabTextBlack,
        obscureText: state.formData[key]!['obsecure'],
        errorText: errorText ?? state.formData[key]!['errorText'],
        showLeftIcon: true,
        showRightIcon: showRightIcon,
        rightWidget: rightWidget,
        leftWidget: Row(
          children: [
            MyAssetImage(leftIconRes, width: leftIconWidth, height: leftIconHeight),
            const Spacer(),
            Container(
              color: ColorConstants.graye5,
              width: 1,
              height: 15,
            )
          ],
        ).constrained(width: 30),
      ),
    );
  }
}
